<?php

defined('BASEPATH') OR exit('No direct script access allowed');


class Cron extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
		$this->load->model(['sitedisapproved_model','job_model','goods_model','site_model','sitecategory_model','siteproduct_model','siteorder_model','siteuser_model','sf_model','systemconfig_model']);
    }

    public function sfset()
    {

        $cdlist = $this->sf_model->get_cdlist();
        $total = $success = $fail = 0;
        if($cdlist)
        {   $total=count($cdlist);

            $expressorder=[];
            $config = $this->systemconfig_model->get_configs();
            $this->load->library('libsfexpress',["apiid"=>$config["sfapiid"],"apikey"=>$config["sfapikey"]]);
            foreach($cdlist as $sfitem)
            {
                $sfresult=$this->libsfexpress->createsforder($sfitem);
                if($sfresult["status"]!=0)
                {
                    $success++;
                    $newdata=["sfordersn"=>$sfresult["id"]];
                    $this->sf_model->update($sfitem["id"],$newdata);
                    if($sfitem["orderid"]>0)
                    {
                        $expressorder[]=["oid"=>$sfitem["orderid"],"shipsn"=>$sfresult["id"]];
                    }
                }
                else
                {
                    $newdata = ["remark"=>$sfresult["msg"]];
                    $this->sf_model->update($sfitem["id"],$newdata);
                    $fail++;
                }
            }

            if($expressorder)
            {
                foreach($expressorder as $shipitem)
                {

                    $order=$this->siteorder_model->getitembyid($shipitem["oid"]);
                    if($order&&$order["siteid"]>0)
                    {

                        $site=$this->site_model->getitembyid($order["siteid"]);
                        if(!empty($site))
                        {
                            loadsystemlink($site);
                            if(!$this->mysite->checklink)
                            {
                                unset($this->mysite);
                                continue;
                            }
                            $newdata=["state"=>4,"shipping"=>$shipitem["shipsn"]];
                            $result = $this->mysite->shiporder($order["oid"],$shipitem["shipsn"]);
                            if($result=="ok")
                            {
                                $this->siteorder_model->update($order["id"], $newdata);
                            }
                            unset($this->mysite);
                        }
                    }
                }
            }
        }
        die("run result : total {$total} orders , success {$success} , fail {$fail}");
    }

    public function t()
    {
        $title="18-88L Stainless Steel Barrel Seal Beer Brewing Wine Beer Whiskey Rum Barrel Port container Storage Oil Milk Rice Barrel";
        echo $this->refixtitle($title);
        die();

    }

    private function get_url_status($url,$millisecond=3000)
    {
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_TIMEOUT_MS,$millisecond);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch,CURLOPT_NOBODY,true);
        curl_exec($ch);
        $rt = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $rt;
    }

    public function checkonline()
    {
        $sites=$this->site_model->getsitetype(1);
        foreach($sites as $site)
        {
            $code=$this->get_url_status($site["domian"]);
            if($code=="200")
            {
                $newdata=["checktime"=>date("Y-m-d H:i:s"),"checkonline"=>1];
            }
            else
            {
                $newdata=["checktime"=>date("Y-m-d H:i:s"),"checkonline"=>0];
            }
            $this->site_model->update($site["id"],$newdata);
            echo $code."\n";
        }

        die("done");
    }

    private function refixtitle($title)
	{

		$config = get_system_settings();
		$mark = explode(PHP_EOL,$config["remove_dot"]);
		foreach($mark as &$m)
		{
			$m=trim($m);
		}
		$key = explode(PHP_EOL,$config["remove_keyword"]);
		foreach($key as &$k)
		{
			$k=trim($k);
		}


		$title=str_ireplace($mark,"",$title);
		$find=[];
		foreach($key as $k)
		{
			$find[]='/\b'.$k.'\b/i';
		}
        $title=preg_replace($find,"",$title);
        $title=preg_replace('/[^\w\s[:punct:]]/i','',$title);
		$title=preg_replace('/\s+/i'," ",$title);
		return ucwords(trim($title));
	}

    private function getservice($config)
    {
        if(!$config["apiauth"]) return;
        $apiauth=$config["apiauth"];
        file_put_contents("./api.json",$apiauth);
        putenv('GOOGLE_APPLICATION_CREDENTIALS=./api.json');
        $client = new Google_Client();
        $client->setApplicationName("My Application");
        $client->useApplicationDefaultCredentials();
        $client->addScope(Google_Service_ShoppingContent::CONTENT);
        $service = new Google_Service_ShoppingContent($client);
        return $service;
    }

    public function cleannosellsite()
    {
        $siteid=118;
        $site=$this->site_model->getitembyid($siteid);
        loadsystemlink($site);
        if(!$this->mysite->checklink)
        {
            echo "请检查接口配置";
            die();
        }
        else
        {
            $products = $this->siteproduct_model->getnosell($siteid);
            if($products)
            {
                foreach($products as $product)
                {
                    $result = $this->mysite->delproduct($product);
                    if($result=="ok")
                    {
                        $this->siteproduct_model->delitem($product["id"]);
                        echo "deleted ".$product["id"]."\n";
                    }
                }
            }
        }

        echo "clean done";
        die();
    }

    public function syncfeed()
    {
        $sites=$this->site_model->getallsync();

        if($sites):

            $this->sitedisapproved_model->truncate();
            foreach($sites as $k=>$site)
            {
                try{

                    $config=json_decode($site["extra"],true);
                    if(!isset($config["merchid"]) || !isset($config["apiauth"])) continue;
                    $merchantId=$config["merchid"];
                    $service=$this->getservice($config);
                    if($service && $merchantId)
                    {
                        echo "sync site ".$site["name"]."\n";
                        $parameters = ['maxResults'=>250];
                        $products = $service->productstatuses->listProductstatuses($merchantId,$parameters);
                        $bansite=false;
                        while (!empty($products->getResources()) && !$bansite) {
                            foreach ($products->getResources() as $product) {
                                if($bansite) break;
                                $fe = false;
                                $newrecord=[];
                                $error = $product->getItemLevelIssues();
                                foreach($error as $e)
                                {
                                    if($e["servability"]=="disapproved")
                                    {
                                        if($e["code"]=="policy_enforcement_account_disapproval")
                                        {
                                            $bansite=true;
                                            break;
                                        }
                                        $fe=true;
                                        $newrecord["code"]=$e["code"];
                                        $newrecord["skuid"]=$product->getProductId();
                                        $newrecord["siteid"]=$site["id"];
                                        $tmp=explode("_",$newrecord["skuid"]);
                                        if(count($tmp)>1)
                                        $newrecord["prid"]=$tmp[1];
                                        else
                                        $newrecord["prid"]=str_replace("online:en:US:","",$tmp[0]);
                                        $newrecord["title"]=$product->getTitle();
                                        $newrecord["description"]=$e["description"];
                                        $newrecord["link"]=$product->getLink();
                                        break;
                                    }
                                }
                                if($fe)
                                {
                                    $this->sitedisapproved_model->create($newrecord);
                                }
                            }

                            if (empty($products->getNextPageToken())) {
                                break;
                            }
                            $parameters['pageToken'] = $products->nextPageToken;
                            echo "fetch next page ".$parameters['pageToken']."\n";
                            $products = $service->productstatuses->listProductstatuses($merchantId, $parameters);
                        }


                        $totalnum=0;
                        $params['maxResults']=250;
                        while (true) {
                            $productsresource = $service->products->listProducts($merchantId, $params);
                            $totalnum+=$productsresource->count();
                            $lastPageToken=$productsresource->getNextPageToken();
                            if (empty($lastPageToken)) break;
                            $params['pageToken']=$productsresource->nextPageToken;
                        }
                        $newdata=[
                            "feedcount"=>$totalnum,
                            "feedsynctime"=>date("Y-m-d H:i:s")
                        ];
                        $this->site_model->update($site["id"],$newdata);
                        unset($service);
                    }


                }catch(Exception $e){
                    $message=trim($e->getmessage());
                    file_put_contents("./logs/".date("Ymd")."feed.text",$message."\n",FILE_APPEND | LOCK_EX);
                }
            }
        endif;
        echo "sync done";
        die();
    }


    public function syncsite()
    {
        echo "start sync..\n";
        $sites=$this->site_model->getallsync();
        if($sites):
            foreach($sites as $k=>$site)
            {

                try{
                    echo "sync ".$site["name"]."... \n";

                    loadsystemlink($site);
                    if(!$this->mysite->checklink)
                    {
                        echo "error";
                        unset($this->mysite);
                        continue;
                    }
                    $maxid=$this->siteorder_model->max("oid",["siteid"=>$site["id"]]);
                    if(!$maxid)
                    {
                        $maxid=0;
                    }
                    $page=1;
                    $exist=0;

                    while (1)
                    {

                        $result=$this->mysite->syncenquiry($page,$maxid);
                        if($result["data"])
                        {

                            foreach($result["data"] as $item)
                            {
                                $ip = $item["ip_address"];
                                if (filter_var($ip, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
                                    $ip_area = $this->site_model->get_ipv6($ip);
                                    $country = $ip_area;
                                }else{
                                    $ip_address = $this->site_model->get_ipv4($ip);
                                    $country = $ip_address["country"];
                                }
                                $check=$this->siteorder_model->get_item_by_where(["siteid"=>$site["id"],"oid"=>$item["entry_id"]]);
                                if($check)
                                {
                                    $exist=1;
                                }
                                else
                                {
                                    $detail = json_decode($item["fields"],true);
                                    $newdata = [
                                        "siteid"=>$site["id"],
                                        "ipaddr"=>$item["ip_address"],
                                        "agent"=>$item["user_agent"],
                                        "addtime"=>$item["date"],
                                        "url"=>$item["url"],
                                        "oid"=>$item["entry_id"],
                                        "state"=>0,
                                        "realname"=>$detail[0]["value"],
                                        "email"=>$detail[2]["value"],
                                        "phone"=>$detail[3]["value"],
                                        "info"=>$detail[4]["value"],
                                        "country" =>$country,
                                        "quantity"=>isset($detail[12]["value"])?$detail[12]["value"]:"null",
                                    ];
                                    $this->siteorder_model->create($newdata);
                                }
                            }

                            if(count($result["data"])<50||$exist==1)
                            {
                                break;
                            }
                            $page++;
                        }
                        else
                        {
                            break;
                        }

                    }

                }
                catch(Exception $e)
                {
                    $message=trim($e->getmessage());
                    file_put_contents("./logs/".date("Ymd")."sync.text",$message."\n",FILE_APPEND | LOCK_EX);
                }
                unset($this->mysite);
            }
        endif;
        die("ok");
    }

    public function updatelimitsite()
    {
        $this->job_model->limitupdate();
        echo "ok";
        die();
    }

    private function filterimg($img)
    {
        $config = get_system_settings();
        if($img && is_array($img))
        {
            foreach($img as &$im)
            {
                if(substr($im,0,4)!="http")
                {
                    $im=$config["urlpath"]."/".$im;
                }
            }
        }
        return $img;
    }

    public function testgood($id)
    {

        $site = $this->site_model->getitembyid(2);
        loadsystemlink($site);
        $priceruler="def:plus#3";
        $good=$this->goods_model->getbyid($id);
        $good["vendor"]="default";
        $good["catename"]="test";
        $good["sku"]="test";
        $good=$this->prefiltergood($good,$priceruler,0);
        $formatgood=$this->mysite->testproduct($good);
        print_r($formatgood);
    }
    private function prefiltergood($good,$fixoption=1)
    {
        $newdata=[];
        $good["shippingfee"] = str_replace([",","$","US"],"",$good["shippingfee"]);
        //title
        $newtitle=$this->refixtitle($good["name"]);
        if($newtitle && $newtitle!=$good["name"])
        {
            $newdata["name"]=$newtitle;
            $newdata["oname"]=$good["name"];
            $good["name"]=$newtitle;
        }

        $good["thumb"]=unserialize($good["thumb"]);
        $good["thumb"]=$this->filterimg($good["thumb"]);
        $good["option"]=unserialize($good["option"]);

        //option check
        $ogoptuion=$good["option"];
        $newoption=[];
        $optionname=[];
        if($good["option"] && isset($good["option"]["newsku"])){
            $newoption["newsku"]=$good["option"]["newsku"];
            foreach($good["option"]["newsku"] as $k=>$v)
            {
                $v["price"]=str_replace([",","$","US"],"",$v["price"]);
                $good["option"]["newsku"][$k]["price"]=get_price($priceruler,$v["price"])+$good["shippingfee"];
            }
        }

        if($good["option"] && isset($good["option"]["vv"])){
            foreach($good["option"]["vv"] as $k=>$option){
                $option_row=$option;
                if($fixoption==1)
                {
                    if(strstr(strtolower($option["name"]),"color") || strstr(strtolower($option["name"]),"colour"))
                    {
                        $good["option"]["vv"][$k]["name"]="Color";
                    }
                    if(strstr(strtolower($option["name"]),"size"))
                    {
                        $good["option"]["vv"][$k]["name"]="Size";
                    }
                }
                $good["option"]["vv"][$k]["name"]=ucwords($good["option"]["vv"][$k]["name"]);
                if(in_array($good["option"]["vv"][$k]["name"],$optionname))
                {
                    $good["option"]["vv"][$k]["name"].="-".$k;
                }
                $optionname[]=$good["option"]["vv"][$k]["name"];

                $option_row["name"]=$good["option"]["vv"][$k]["name"];
                $vavvcon=[];
                foreach($option_row["value"] as $vakey=>$val)
                {
                    $val=trim($val);
                    if(!in_array($val,$vavvcon))
                    {
                        $option_row["value"][$vakey]=$val;
                        $good["option"]["vv"][$k]["value"][$vakey]=$val;
                        $vavvcon[]=$val;
                    }
                    else
                    {
                        $option_row["value"][$vakey]=$val."-".($vakey+1);
                        $vavvcon[]=$option_row["value"][$vakey];
                        $good["option"]["vv"][$k]["value"][$vakey]=$option_row["value"][$vakey];
                    }
                }
                $newoption["vv"][]=$option_row;

                if(isset($option["price"]))
                {
                    foreach($option["price"] as $k1=>$v1)
                    {
                        $v1=str_replace([",","$","US"],"",$v1);
                        $good["option"]["vv"][$k]["price"][$k1]=get_price($priceruler,$v1)+$good["shippingfee"];
                    }
                }
            }
        }
        if($newoption!=$ogoptuion)
        {
            $newdata["option"]=serialize($newoption);
        }


        if($newdata)
        {
            $this->goods_model->update($good["id"],$newdata);
        }

        return $good;
    }


    private function check_job()
    {
        exec("ps -Af|grep do_job",$output,$return);
        $count = 0;
        if($output){
            foreach($output as $row){
                if(strpos($row,'index.php') !== false){
                    $count++;
                }
            }
        }
        if($count>1){
            return 'check success';
        }
        $jobs=$this->job_model->getstarting();
        if($jobs):
		foreach($jobs as $job)
		{
			$this->job_model->update($job["id"], ["status"=>0]);
        }
        endif;
        return 'success';
    }



    public function do_job()
    {
        ini_set('memory_limit','2G');

        $this->check_job();
        $job=null;
        $wait=$this->job_model->getwaiting();
        if(!$wait)
        {
          die("no job");
        }
        else
        {
            $start=$this->job_model->getstarting();
            if(!$start)
            {
                $job=$wait[0];
            }
            else
            {
                $canstart=[1,1,1];
                foreach($start as $s)
                {
                    $d=json_decode($s["filter"],true);
                    $site = $this->site_model->getitembyid($d["siteid"]);
                    $canstart[$site["sitetype"]-1]=0;
                }
                foreach($wait as $w)
                {
                    $d=json_decode($w["filter"],true);
                    $site = $this->site_model->getitembyid($d["siteid"]);
                    if($canstart[$site["sitetype"]-1]==1){
                        $job=$w;
                        break;
                    }
                }
            }
        }


        if($job)
        {

            $this->job_model->start($job);
            switch($job["job_type"])
            {
                case "batchpush":
                case "pushall":
                    $filter=json_decode($job["filter"],true);
                    $site = $this->site_model->getitembyid($filter["siteid"]);
                    $site["extra"] = json_decode($site["extra"],true);
                    $category = $this->sitecategory_model->getitembyid($filter["catid"]);
                    $goods=$this->goods_model->get_filter_goods($filter);
                    if($goods)
                    {
                        //$this->load->library('sitetype/prestashop',$site,'mysite');
                        loadsystemlink($site);

                        $pushcount=0;

                        foreach($goods as $good)
                        {

                            if($this->existprr($good["id"],$site["id"]))
                            {
                                echo "exist\n";
                                continue;
                            }
                            $fixoption=1;
                            if($site["sitetype"]!=1) $fixoption=0;
                            $good=$this->prefiltergood($good,$fixoption);
                            $good["catename"]=$category["name"];
                            $good["rid"]=$category["rid"];


                            if($good["source"]=="aliexpress" && $good["meta"])
                            {
                                $extra=json_decode($good["meta"],true);
                                $extra["meta"]=str_ireplace("China Suppliers",ucfirst(str_replace("https://www.","",$site["domain"])),$extra["meta"]);
                                $extra["meta"]=trim(str_ireplace("Enjoy ✓Free Shipping Worldwide! ✓Limited Time Sale ✓Easy Return.","",$extra["meta"]));
                                $extra["keyword"]=trim(str_replace(", ,","",$extra["keyword"]));
                                $good["meta"]=json_encode($extra,JSON_UNESCAPED_UNICODE);
                            }
                            if(isset($site["extra"]["goodtmpl"]))
                            {
                                $good["goodtmpl"]=$site["extra"]["goodtmpl"];
                            }
                            else
                            {
                                echo "no goods tmpl setup";
                                break;
                            }


                            $result=$this->mysite->addproduct($good);
                            /*
                            if(isset($result["limit"]) && $result["limit"]==1)
                            {
                                $this->job_model->update($job["id"],["status"=>5,"endtime"=>date("Y-m-d H:i:s")]);
                                die();
                            }
                            */
                            if($result["rs"]==1)
                            {
                                $result["data"]["postid"]?$good["prid"]=$result["data"]["postid"]:$good["prid"]=null;
                                $good["url"]=$result["data"]["url"];
                            }

                            if($good["prid"]&&!$this->existpr($good,$site["id"]))
                            {
                                $this->site_model->addgcount($site["id"]);
                                $this->addproduct($good,$site["id"]);
                                $this->goods_model->addpushcount($good["id"]);
                                $this->job_model->addjobcount($job["id"]);
                            }else{
                                echo "no goods prid";
                                break;
                            }
                            $pushcount++;
                        }
                    }

                    break;
            }
            $this->job_model->done($job);
        }
        die("ok");
    }

    private function existprr($ogid,$siteid)
    {
        $where=["productid"=>$ogid,"siteid"=>$siteid];
        return $this->siteproduct_model->getitemkeyfilter($where);
    }


    private function existpr($good,$siteid)
    {
        $where=["rid"=>$good["prid"],"siteid"=>$siteid];
        return $this->siteproduct_model->getitemkeyfilter($where);
    }

    public function addproduct($good,$siteid)
    {
        $newdata=[
            "siteid"=>$siteid,
            "productid"=>$good["id"],
            "price"=>$good["price"],
            "title"=>$good["name"],
            "rid"=>$good["prid"],
            "cid"=>$good["rid"],
        ];
        if(isset($good["url"]))
        {
            $newdata["url"]=$good["url"];
        }
        $this->siteproduct_model->create($newdata);
    }
}